#include "filter.h"
#include <stdint.h>
#include <string.h>



int avg_filter_input(TAvgFilter* filter, int value)
{
	if(filter){
		filter->buf[filter->head++] = value;
		if(filter->head >= filter->depth){
			filter->head = 0;
			filter->init = 1;
		}
		if(filter->init){
			uint64_t sum = 0;
			int        i = 0;
			for(; i < filter->depth; i++){
				sum += filter->buf[i];
			}
			return sum / filter->depth;
		}
	}

	return value;
}
int avg_filter_init(TAvgFilter* filter, unsigned int depth)
{
	if(filter){
		filter->head  = 0;
		filter->depth = (depth > MAX_FILTER_LEN)?MAX_FILTER_LEN:depth;
		filter->init  = 0;
		memset(filter->buf , 0 , MAX_FILTER_LEN*sizeof(int));
		if(filter->depth == 0) filter->depth = 1;
		return filter->depth;
	}
	return FILTER_INVALID_VAL;
}

